<template>
    <view class="blood-container">
        <CmsTabs :type="4" :page-title="'人道救助'" @project-tab-change="handleProjectTabChange" @data-loaded="handleDataLoaded">
            <view class="footer-btn" v-if="currentProjectIndex === -1">
                <!-- <view class="primary-btn" @click="handleGoRegister">我要登记</view> -->
            </view>
        </CmsTabs>

        <!-- 我要登记弹窗 -->
        <view class="register-popup" v-if="showRegisterPopup" @click="handleClosePopup">
            <view class="popup-mask"></view>
            <view class="popup-content" @click.stop>
                <view class="popup-header">
                    <view class="popup-title">救助登记</view>
                    <view class="popup-close" @click="handleClosePopup">×</view>
                </view>
                <view class="popup-form">
                    <view class="form-item">
                        <view class="form-label">姓名<text class="required">*</text></view>
                        <input class="form-input" v-model="formData.name" placeholder="请输入" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">手机号<text class="required">*</text></view>
                        <input class="form-input" v-model="formData.phone" placeholder="请输入" type="number" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">身份证号<text class="required">*</text></view>
                        <input class="form-input" v-model="formData.idno" placeholder="请输入" />
                    </view>
                    <view class="form-item">
                        <view class="form-label">救助类型<text class="required">*</text></view>
                        <view class="form-input-area">
                            <picker @change="handleRescueTypeChange" :value="formData.helpTypeId" :range="rescueTypeOptions" range-key="name" :disabled="rescueTypeOptions.length <= 1">
                                <view class="picker-text">{{ getSelectedRescueTypeName() }}</view>
                            </picker>
                            <image src="../../static/right.png" mode="widthFix" class="right-icon"></image>
                        </view>
                    </view>
                </view>
                <view class="popup-footer">
                    <view class="primary-btn" @click="handleConfirmRegister" :class="{ 'disabled': submitting }">
                        {{ submitting ? '提交中...' : '确认登记' }}
                    </view>
                </view>
            </view>
        </view>

        <!-- 登记成功弹窗 -->
        <view class="success-popup" v-if="showSuccessPopup" @click="handleCloseSuccessPopup">
            <view class="popup-mask"></view>
            <view class="success-popup-content" @click.stop>
                <view class="success-icon">
                    <image src="../../static/success2.png" mode="widthFix" />
                </view>
                <view class="success-title">登记成功</view>
                <view class="success-message">感谢您的申请，后续会有红十字会工作人员与您联系。</view>
                <view class="success-btn" @click="handleCloseSuccessPopup">
                    <text class="btn-text">我知道了</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
    import { ref, onMounted } from 'vue'
    import CmsTabs from '@/components/cms-tabs/cms-tabs.vue'
    import { getRescueTypeList, helpCheckIn } from '@/utils/api.js'
    import { handleFormButtonClick, handleLoginRequiredPopup } from '@/utils/loginGuard.js'

    // 弹窗控制
    const showRegisterPopup = ref(false)
    // 成功弹窗显示状态
    const showSuccessPopup = ref(false)
    // 提交中状态
    const submitting = ref(false)
    // 当前项目tab索引
    const currentProjectIndex = ref(-1)
    
    // 表单数据
    const formData = ref({
        name: '',
        phone: '',
        idno: '',
        helpTypeId: -1
    })

    // 救助类型选项
    const rescueTypeOptions = ref([])

    // 获取救助类型
    const fetchRescueTypes = async () => {
        try {
            const res = await getRescueTypeList()
            if (res.code === 0 && res.data && res.data.length > 0) {
                rescueTypeOptions.value = res.data.map(item => ({
                    name: item.name,
                    id: item.id
                }))
            }
        } catch (error) {
            console.error('获取救助类型失败:', error)
        }
    }

    onMounted(() => {
        fetchRescueTypes()
    })

    // 处理项目tab切换事件
    const handleProjectTabChange = (event) => {
        console.log('项目tab切换:', event)
        // 更新当前项目tab索引
        currentProjectIndex.value = event.index
    }

    // 处理数据加载完成事件
    const handleDataLoaded = (event) => {
        console.log('数据加载完成:', event)
    }

    // 我要登记
    const handleGoRegister = async () => {
        // 检查登录状态，如果未登录会弹出登录提示
        const canShowPopup = await handleLoginRequiredPopup('/pages/jiuzhu/index')
        if (canShowPopup) {
            showRegisterPopup.value = true
        }
    }

    // 关闭弹窗
    const handleClosePopup = () => {
        showRegisterPopup.value = false
        // 重置表单数据
        formData.value = {
            name: '',
            phone: '',
            idno: '',
            helpTypeId: -1
        }
    }

    // 关闭成功弹窗
    const handleCloseSuccessPopup = () => {
        showSuccessPopup.value = false
    }

    // 确认登记
    const handleConfirmRegister = async () => {
        // 表单验证
        if (!validateForm()) {
            return
        }
        
        // 防止重复提交
        if (submitting.value) {
            return
        }
        
        submitting.value = true
        
        try {
            // 获取选中的救助类型ID
            const selectedType = rescueTypeOptions.value[formData.value.helpTypeId]
            if (!selectedType) {
                uni.showToast({
                    title: '救助类型数据错误',
                    icon: 'none'
                })
                return
            }

            // 构建提交数据
            const submitData = {
                name: formData.value.name,
                phone: formData.value.phone,
                idno: formData.value.idno,
                helpTypeId: selectedType.id
            }

            const res = await helpCheckIn(submitData)
            if (res.code === 0) {
                // 显示成功弹窗
                showSuccessPopup.value = true
                
                // 关闭表单
                handleClosePopup()
            } else {
                uni.showToast({
                    title: res.msg || '登记失败',
                    icon: 'none'
                })
            }
        } catch (error) {
            console.error('登记失败:', error)
            uni.showToast({
                title: '登记失败，请重试',
                icon: 'none'
            })
        } finally {
            submitting.value = false
        }
    }

    // 表单验证
    const validateForm = () => {
        const { name, phone, idno, helpTypeId } = formData.value
        
        // 必填验证
        if (!name.trim()) {
            uni.showToast({
                title: '请输入姓名',
                icon: 'none'
            })
            return false
        }
        
        if (!phone.trim()) {
            uni.showToast({
                title: '请输入手机号',
                icon: 'none'
            })
            return false
        }
        
        if (!idno.trim()) {
            uni.showToast({
                title: '请输入身份证号',
                icon: 'none'
            })
            return false
        }
        
        // 救助类型验证
        if (helpTypeId < 0) {
            uni.showToast({
                title: '请选择救助类型',
                icon: 'none'
            })
            return false
        }
        
        // 手机号格式验证
        if (!validatePhone(phone)) {
            uni.showToast({
                title: '手机号格式不正确',
                icon: 'none'
            })
            return false
        }
        
        // 身份证号格式验证
        if (!validateIdCard(idno)) {
            uni.showToast({
                title: '身份证号格式不正确',
                icon: 'none'
            })
            return false
        }
        
        return true
    }
    
    // 身份证号验证
    const validateIdCard = (idCard) => {
        // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
        const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        return reg.test(idCard)
    }
    
    // 手机号验证
    const validatePhone = (phone) => {
        // 手机号格式验证：1开头，第二位是3-9，后面9位数字
        const reg = /^1[3-9]\d{9}$/
        return reg.test(phone)
    }

    // 处理救助类型选择
    const handleRescueTypeChange = (e) => {
        const value = e.detail.value
        formData.value.helpTypeId = value
    }

    // 获取选中的救助类型名称
    const getSelectedRescueTypeName = () => {
        if (formData.value.helpTypeId >= 0 && rescueTypeOptions.value[formData.value.helpTypeId]) {
            return rescueTypeOptions.value[formData.value.helpTypeId].name
        }
        return rescueTypeOptions.value.length <= 1 ? '加载中...' : '请选择'
    }
</script>

<style lang="scss" scoped>  
    .blood-container{
        padding-bottom: 140rpx;
    }

    .footer-btn{
        position: fixed;
        bottom: 0;
        left: 0;
        width: calc(100% - 48rpx);
        height: 100rpx;
        background: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 24rpx 24rpx 28rpx 24rpx;
        z-index: 100;
    }

    // 登记弹窗样式
    .register-popup {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 999;
        display: flex;
        align-items: flex-end;

        .popup-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
        }

        .popup-content {
            position: relative;
            width: 100%;
            max-height: 85vh;
            min-height: 500rpx;
            background: #FFFFFF;
            border-radius: 24rpx 24rpx 0rpx 0rpx;
            z-index: 1000;
            display: flex;
            flex-direction: column;

            .popup-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 32rpx 24rpx 24rpx 24rpx;
                position: relative;
                flex-shrink: 0;
                border-bottom: 2rpx solid #f0f0f0;

                .popup-title {
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    font-size: 32rpx;
                    line-height: 44rpx;
                    font-weight: 500;
                    color: #000;
                    text-align: center;
                }

                .popup-close {
                    width: 48rpx;
                    height: 48rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 40rpx;
                    color: rgba(0, 0, 0, 0.90);
                    cursor: pointer;
                    margin-left: auto;
                }
            }

            .popup-form {
                flex: 1;
                overflow-y: auto;
                padding: 0 24rpx;

                .form-item {
                    display: flex;
                    align-items: center;
                    padding: 24rpx 0;
                    border-bottom: 2rpx solid #E7E7E7;

                    &:last-child {
                        border-bottom: none;
                        padding-bottom: 32rpx;
                    }

                    &:first-child {
                        padding-top: 32rpx;
                    }

                    .form-label {
                        width: 160rpx;
                        font-size: 28rpx;
                        color: rgba(0, 0, 0, 0.60);
                        flex-shrink: 0;

                        .required {
                            color: #F9623E;
                            margin-left: 4rpx;
                        }
                    }

                    .form-input {
                        flex: 1;
                        text-align: right;
                        font-size: 28rpx;
                        border: none;
                        outline: none;
                        background: transparent;

                        &::placeholder {
                            color: rgba(0, 0, 0, 0.40);
                        }
                    }

                    .form-input-area {
                        flex: 1;
                        text-align: right;
                        display: flex;
                        align-items: center;
                        justify-content: flex-end;

                        .picker-text {
                            font-size: 28rpx;
                            color: rgba(0, 0, 0, 0.40);
                            margin-right: 8rpx;
                        }

                        .right-icon {
                            width: 24rpx;
                            height: 24rpx;
                            flex-shrink: 0;
                        }
                    }
                }
            }

            .popup-footer {
                flex-shrink: 0;
                padding: 24rpx;
                border-top: 2rpx solid #E7E8EB;
                background: #FFFFFF;

                .primary-btn {
                    width: 100%;
                    height: 88rpx;
                    background: linear-gradient(135deg, #F9623E 0%, #FF7A5A 100%);
                    border-radius: 44rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #FFFFFF;
                    font-size: 32rpx;
                    font-weight: 500;
                    box-shadow: 0 8rpx 24rpx rgba(249, 98, 62, 0.3);
                    transition: all 0.3s ease;

                    &:active {
                        transform: scale(0.98);
                        box-shadow: 0 4rpx 12rpx rgba(249, 98, 62, 0.3);
                    }
                }
            }
        }
    }

    // 成功弹窗样式
    .success-popup {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;

        .popup-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
        }

        .success-popup-content {
            position: relative;
            width: 600rpx;
            background: #FFFFFF;
            border-radius: 24rpx;
            padding: 48rpx 32rpx;
            text-align: center;
            box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.2);

            .success-icon {
                width: 120rpx;
                height: 120rpx;
                margin: 0 auto 32rpx;
                display: flex;
                align-items: center;
                justify-content: center;

                image {
                    width: 100%;
                    height: 100%;
                }
            }

            .success-title {
                font-size: 36rpx;
                font-weight: 600;
                color: #000000;
                margin-bottom: 24rpx;
                line-height: 1.4;
            }

            .success-message {
                font-size: 28rpx;
                color: rgba(0, 0, 0, 0.6);
                line-height: 1.6;
                margin-bottom: 48rpx;
                padding: 0 16rpx;
            }

            .success-btn {
                width: 100%;
                height: 88rpx;
                background: linear-gradient(135deg, #F9623E 0%, #FF7A5A 100%);
                border-radius: 44rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 8rpx 24rpx rgba(249, 98, 62, 0.3);
                transition: all 0.3s ease;

                &:active {
                    transform: scale(0.98);
                    box-shadow: 0 4rpx 12rpx rgba(249, 98, 62, 0.3);
                }

                .btn-text {
                    color: #FFFFFF;
                    font-size: 32rpx;
                    font-weight: 500;
                }
            }
        }
    }
</style>